package com.leyou.auth.service.impl;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.AuthService;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.CookieUtils;
import com.leyou.item.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties jwtProperties;

//    登录授权
    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            UserDTO userDTO = this.userClient.login(username, password);

/*//        判断
            if(null == userDTO){
                throw new LyException(ExceptionEnum.USER_NOT_FOUND);
            }*/

//        不为空得到信息，生成token
            UserInfo userInfo = BeanHelper.copyProperties(userDTO, UserInfo.class);

            userInfo.setRole("admin");

            String token = JwtUtils.generateTokenExpireInMinutes(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getUser().getExpire());

//        TODO 把toten保存到cook中
/*
            Cookie cookie = new Cookie(jwtProperties.getUser().getCookName(), token);
            cookie.setMaxAge(jwtProperties.getUser().getExpire()*60);
//        js不可操作，前端隐藏
            cookie.setHttpOnly(true);
//        设置路径为所有
            cookie.setPath("/");
            cookie.setDomain(jwtProperties.getUser().getCookieDomain());
            response.addCookie(cookie);*/

            CookieUtils.newBuilder()
                    .maxAge(jwtProperties.getUser().getExpire()*60)
                    .domain(jwtProperties.getUser().getCookieDomain())
                    .httpOnly(true)
                    .value(token)
                    .response(response)
                    .build();
        } catch (LyException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.USER_NOT_FOUND);
        }
    }
}
